import React from 'react';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Form, Input, message, Alert } from 'antd';
import type { FormProps } from 'antd';
import Card from 'antd/es/card/Card';
import { InsuranceTwoTone } from '@ant-design/icons';
import '../index.css'
import link from "../utils/link.tsx";
import Url from '../utils/url.tsx';
import { useNavigate } from 'react-router-dom';

const login: React.FC = () => {

  {/* --登录校验-- */ }
  type FieldType = {
    username?: string;
    password?: string;
  };
  const navigate = useNavigate();
  const [messageApi, contextHolder] = message.useMessage();

  const success = () => {
    messageApi.open({
      type: 'success',
      content: '登录成功',
    });
  };

  const error = () => {
    messageApi.open({
      type: 'error',
      content: '登录失败，请检查账号和密码是否输入正确',
    });
  };

  const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
    link(Url.login, "post", {}, { account: values.username, password: values.password }).then((ok: any) => {
      if (ok.data.code == 1) {
        success()
        localStorage.setItem("bku_token", ok.data.data)
        link(Url.userInfo, "get", {}, {}).then((ok: any) => {
          if (ok.data.code == 1) {
            localStorage.setItem("bku_username", ok.data.data.username)
            localStorage.setItem("bku_power", ok.data.data.power)
            navigate('/layout')
          }
        })
      }
      else
        error()
    })
  };

  {/* --return界面-- */ }
  return (
    <Card className='login_box'>
      {contextHolder}
      <InsuranceTwoTone className='login_icon' />
      <h1 style={{ display: 'inline-block' }}>数据备份软件</h1>
      <Form
        name="login"
        initialValues={{ remember: true }}
        style={{ maxWidth: 360 }}
        onFinish={onFinish}
      >
        <Form.Item
          name="username"
          rules={[{ required: true, message: '账号不能为空' }]}
        >
          <Input prefix={<UserOutlined />} placeholder="请输入账号" />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[{ required: true, message: '密码不能为空' }]}
        >
          <Input prefix={<LockOutlined />} type="password" placeholder="请输入密码" />
        </Form.Item>

        <Form.Item>
          <Button block type="primary" htmlType="submit">
            登录
          </Button>
          <Alert style={{ marginTop: '15px' }} message="新账号请使用初始密码登录，并尽快修改密码！" type="info" showIcon closable />
        </Form.Item>
      </Form>
    </Card>

  );
};

export default login;